<template>
    <div class="btn">
        <a-button @click="saveXMLs">保存</a-button>
        <a-button @click="saveDiagram">下载</a-button>
        <a-button @click="saveImg">生成图片</a-button>
    </div>
  <div class="containerBox" style="position: relative;">
    <div id="container" style="width: calc(100vw - 420px); height: calc(100vh - 20px)">
    </div>
    <div id="js-properties-panel" class="panel"></div>
  </div>
</template>

<script setup>
import { onMounted, markRaw } from 'vue';
//bpm-js相关
import BpmnModeler from 'bpmn-js/lib/Modeler';
import 'bpmn-js/dist/assets/diagram-js.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css';
//bpmn-js-properties-panel相关
import 'bpmn-js-properties-panel/dist/assets/bpmn-js-properties-panel.css'
import propertiesPanelModule from 'bpmn-js-properties-panel'
import propertiesProviderModule from 'bpmn-js-properties-panel/lib/provider/camunda'
import camundaModdleDescriptor from 'camunda-bpmn-moddle/resources/camunda'
//引入汉化js
import { customTranslate } from '../../../../translate/translations';
import html2canvas from 'html2canvas';
import axios from 'axios';
import {useRouter} from 'vue-router'
const router=useRouter();
let bpmnModeler;
onMounted(() => {
  const containerEl = document.getElementById('container');
  bpmnModeler = markRaw(new BpmnModeler({
    container: containerEl,
    //添加控制板
    propertiesPanel: {
      parent: '#js-properties-panel'
    },
    //右侧属性面板
    additionalModules: [
      propertiesPanelModule,
      propertiesProviderModule,
      {
        translate: ["value", customTranslate]
      }
    ],
    moddleExtensions: {
      camunda: camundaModdleDescriptor
    }
  }));
  bpmnModeler.createDiagram(() => {
    bpmnModeler.get('canvas').zoom('fit-viewport');
  });


  //删除logo
  const bjsIoLogo = document.querySelector('.bjs-powered-by');
  while (bjsIoLogo?.firstChild) {
    bjsIoLogo.removeChild(bjsIoLogo.firstChild)
  }
});
//保存
const saveXMLs=()=>{
    bpmnModeler.saveXML({ format: true }, (err, xml) => {
    if (err) {
      console.error('Error saving BPMN diagram', err);
      return;
    }
    // console.log('输出的XML:', xml);
    //将生成XML字符串转为Blob文件
    const xmlBlob=new Blob([xml],{type:'application/xml'});
    const xmlFile=new File([xmlBlob],'bpmn20.bpmn',{type:'application/xml'});
    //构建表单
    const formData=new FormData();
    formData.append('file',xmlFile);
    // 向后端发送 XML 数据
    axios.post('http://192.168.1.102:8111/jeecg-boot/process/askForLeave/deploy', formData,
      {
        headers:{
          'X-Access-Token':'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MzE4Njk0OTcsInVzZXJuYW1lIjoiYWRtaW4ifQ.Br1QcedYH4aN9FXkuMR2hM4HqiA2i7XfPtgzQeivcbo',
          'Content-Type':'multipart/form-data'
        }
      }
    )
      .then(response => {
        console.log('成功的状态:', response);
       // const newFileInfo = response.data;
        //获取右侧属性面板的流程名字和编号
        // const elementRegistry = bpmnModeler.get('elementRegistry');
        // const selectedElement = elementRegistry.get('id');
        // const propertiesPanel=bpmnModeler.get('propertiesPanel');
        // const processName=selectedElement.get('name')
        // const processCode = selectedElement.get('code');

        // 获取当前时间
        const currentTime = new Date().toLocaleString();

       //跳转传递数据
       router.push({
        path:'/system/process',
        query:{newProcessData:JSON.stringify({
          // name:processName,
          // code:processCode,
          timestamp:currentTime
        })}
       })

      })
      .catch(error => {
        console.error('失败的状态:', error);
      });
  });
}
// 下载XML
const saveDiagram = () => {
  bpmnModeler.saveXML({ format: true }, (err, xml) => {
    if (err) {
      console.error('下载失败', err);
      return;
    }
    // 创建一个下载链接
    const blob = new Blob([xml], { type: 'application/xml' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'bpmn20.bpmn';  // 设置下载文件名
    link.click();  // 自动触发下载
  });
};

//生成图片
const saveImg=()=>{
  const container = document.getElementById('container');
  html2canvas(container).then(canvas => {
    const imgURL = canvas.toDataURL('image/png');
    const link = document.createElement('a');
    link.href = imgURL;
    link.download = 'bpmn-diagram.png';
    link.click();
  });
}

</script>

<style scoped>
.containerBox {
  background-image: conic-gradient(at calc(100% - 1px) calc(100% - 1px),#eee 270deg ,#fff 0),
    conic-gradient(at calc(100% - 1px) calc(100% - 1px),#eee 270deg,#fff 0);
  background-size: 50px 50px;
}

.containerBox #container {
  height: calc(100vh - 100px);
  border: 1px solid rgb(121, 121, 121);
}

.bpp-properties-panel [type=text] {
  box-sizing: border-box;
}

.panel {
  width: 300px;
  position: absolute;
  top: 1px;
  right: 1px;
  height: 100%;
  overflow: auto;
}

.bjs-powered-by {
  display: none !important;
}

.btn {
    width: 15vw;
    height: 5vh;
    position: absolute;
    top: 10px;
    left: 150px;
    z-index: 10;
    display: flex;
    justify-content: space-between;
}
</style>
